/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jsf;

import com.controllers.CompanyDenominationController;
import com.controllers.CreditController;
import com.controllers.CrudUtil;
import com.controllers.TransactionController;
import com.entities.CompanyDenomination;
import com.entities.Credit;
import com.entities.Transactions;
import com.mpowerpayments.mpower.MPowerCheckoutStore;
import com.mpowerpayments.mpower.MPowerOnsiteInvoice;
import com.mpowerpayments.mpower.MPowerSetup;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.primefaces.event.FlowEvent;

/**
 *
 * @author ben
 */
@Named(value = "purchase")
@SessionScoped
public class Purchase implements Serializable {

    /**
     * Creates a new instance of Purchase
     */
    
   String host = "smtp.gmail.com";
        String port = "587";
        String username = "purcase.qrcodes@gmail.com";
        String password = "!purchase.qrcodes!";
        
    public Purchase() {

        quantity = 1;
        
        voucher = new CompanyDenomination();

    }
    private String mpowerAccountNumber;
    @EJB
    private CompanyDenominationController companyDenominationController;
    @EJB
    private CrudUtil crudUtil;
    
    @EJB
    private CreditController creditController;
    
    @EJB
    private TransactionController transactionController;
    
    private CompanyDenomination voucher;
    private Credit credit;

    public Credit getCredit() {
        return credit;
    }

    public void setCredit(Credit credit) {
        this.credit = credit;
    }
    
    

    public CompanyDenomination getVoucher() {
        return voucher;
    }

    public void setVoucher(CompanyDenomination voucher) {
        this.voucher = companyDenominationController.findById(voucherId);
        System.out.println(voucher.getCompany().getName());
    }
    private int quantity; //default quantity has to be changed in the future;
    private Long voucherId;
    private String pin;
    private String confirmCode;
    private MPowerOnsiteInvoice invoice;
    String oprToken = null;
    
    private Transactions transactions;

    public Transactions getTransactions() {
        return transactions;
    }

    public void setTransactions(Transactions transactions) {
        this.transactions = transactions;
    }
    
    

    public String getConfirmCode() {
        return confirmCode;
    }

    public void setConfirmCode(String confirmCode) {
        this.confirmCode = confirmCode;
    }
    private double totalAmount;

    public String getMpowerAccountNumber() {
        return mpowerAccountNumber;
    }

    public void setMpowerAccountNumber(String mpowerAccountNumber) {
        this.mpowerAccountNumber = mpowerAccountNumber;
    }

    public String onFlowProcess(FlowEvent event) {
        System.out.println("In " + event.getOldStep() + "  : Current step");

      //  String returnTab = null;
        if (event.getOldStep().equals("approve")) {
            try {
                //Generate pin for user
                System.out.println("Generating Pin for user");


                MPowerSetup mPowerSetup = new MPowerSetup();
                mPowerSetup.setMasterKey("a451a294-2f1e-4d17-8ba4-1e3c22408e31");
                mPowerSetup.setPrivateKey("live_private_1CDm8pFOD2cCW4KfZtFsPHEJQR4");
                mPowerSetup.setPublicKey("live_public_-0YnaZV8H1zYec83YiC_6TtBdro");
                mPowerSetup.setToken("1f3185e8edb8a3bddd1d");
                mPowerSetup.setMode("live");

                MPowerCheckoutStore store = new MPowerCheckoutStore();
                store.setName("Online Credit Reload");
                store.setTagline("Initial Transfer");
                store.setPhoneNumber("0541282818"); // The account that will see an increase in revenue (payee)

                invoice =
                        new MPowerOnsiteInvoice(mPowerSetup, store);

                String item = voucher.getCompany().getName().toString() + " " + voucher.getDenomination().getCurrency().toString()
                        + " " + voucher.getDenomination().getAmount().toString();
                totalAmount = voucher.getDenomination().getAmount() * quantity;
                invoice.addItem(item, quantity, (double) voucher.getDenomination().getAmount(), totalAmount);
                invoice.setTotalAmount(totalAmount);
                oprToken = null;
                if (invoice.create(mpowerAccountNumber)) {
                    System.out.println("OPR Token" + invoice.getToken());
                    oprToken = invoice.getToken();
                    System.out.println("Status" + invoice.getStatus());
                    System.out.println("Response Message" + invoice.getResponseText());
                } else {
                    System.out.println("Status" + invoice.getStatus());
                    System.out.println("Response Message" + invoice.getResponseText());
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error: " + invoice.getResponseText(), "Something went wrong"));
                    return "initialize";

                }
                //      
//       NEXT HALF STEP 
//                if (invoice.create()) {
//                    System.out.println("OPR Token" + invoice.getToken());
//                    oprToken = invoice.getToken();
//                    System.out.println("Status" + invoice.getStatus());
//                    System.out.println("Response Message" + invoice.getResponseText());
//                } else {
//                    System.out.println("Status" + invoice.getStatus());
//                    System.out.println("Response Message" + invoice.getResponseText());
//                    
//                    
//                    System.out.println("The End Of first process");
//                    
//                }
//                
//            }

               return    event.getNewStep();

            } catch (Exception e) {
                e.printStackTrace();
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Network Error. Please check your internet settings", "Something went wrong"));
              //  returnTab = "initialize";
            
            
                            return "initialize";
            }

        }
        else
            return event.getNewStep();
        
        
        


    }

    public String getPin() {
        return pin;
    }

    public void setPin(String pin) {
        this.pin = pin;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public Long getVoucherId() {
        return voucherId;
    }

    public void setVoucherId(Long voucherId) {
        //this.voucherId = voucherId;
        this.voucher = companyDenominationController.findById(voucherId);
    }

    public String save() {
        String returnString = null;
        try {
            
            if (invoice.charge(oprToken, pin)) {
                System.out.println("Status" + invoice.getStatus());
                System.out.println("Response Message" + invoice.getResponseText());
                System.out.println("Receipt URL" + invoice.getReceiptUrl());
                System.out.println("Customer Name" + invoice.getCustomerInfo("name"));
                System.out.println("Customer Email" + invoice.getCustomerInfo("email"));
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Purchase Succesful. Please check your mail for the credit", "Something went wrong"));
 
                // Start of recording and transaction
                credit = new Credit();
                credit =  creditController.getCreditByCompanyDenomination(voucher);
        
                credit.setDateUsed(new Date());
                credit.setUsed(Boolean.TRUE);
                
                transactions = new Transactions();
                transactions.setCredit(credit);
                transactions.setMpowerAccountNumber(mpowerAccountNumber);
                transactions.setTransactionDate(new Date());
                
             
                transactions.setCredit(credit);
                transactions.setCompanyDenomination(voucher);
                crudUtil.update(credit);
                crudUtil.update(transactions);
         
                
//
//                                                                 Properties properties = new Properties();
//                                                                  properties.put("mail.smtp.host", host);
//                                                                 properties.put("mail.smtp.port", port);
//                                                                  properties.put("mail.smtp.auth", "true");
//                                                                 properties.put("mail.smtp.starttls.enable", "true");
//
//
//
//                                                        Session session = Session.getInstance(properties,
//                                                                  new javax.mail.Authenticator() {
//                                                                        protected PasswordAuthentication getPasswordAuthentication() {
//                                                                                return new PasswordAuthentication(username, password);
//                                                                        }
//                                                                  });
//
//                                                       String msgBody = "Hello from the time bomb! Added **********************************";
//
//
//
//
//                                                       try {
//                                                            Message msg = new MimeMessage(session);
//                                                            msg.setFrom(new InternetAddress("purcase.qrcodes@gmail.com", "purchase.qrcodes"));
//                                                            msg.addRecipient(Message.RecipientType.TO,
//                                                                             new InternetAddress("brainychip@gmail.com", "brainychip@gmail.com"));
//                                                            msg.setSubject("Receipt of QR-Code");
//                                                            msg.setText(msgBody);
//
//
//                                                            Multipart mp = new MimeMultipart();
//
//                                                            MimeBodyPart htmlPart = new MimeBodyPart();
//                                                            htmlPart.setContent(msgBody, "text/html");
//                                                            mp.addBodyPart(htmlPart);
//
//
//                                                            MimeBodyPart attachment = new MimeBodyPart();
//                                                            attachment.setFileName("qrcode.jpeg");
//                                                            attachment.setContent(credit.getImage(), "image/jpeg");
//                                                            mp.addBodyPart(attachment);
//
//                                                            msg.setContent(mp);
//
//
//
//
//
//
//
//
//                                                            Transport.send(msg);
//
//                                                            System.out.println("Mail Successfully sent");
//                                                        } catch (AddressException e) {
//                                                            e.printStackTrace();
//                                                        } catch (MessagingException e) {
//                                                            e.printStackTrace();
//                                                        } catch (UnsupportedEncodingException ex) {
//                                                            Logger.getLogger(Experiments.class.getName()).log(Level.SEVERE, null, ex);
//                                                            ex.printStackTrace();
//                                                        }
//
//                                                      // return null;
//
//
//
//
//

                sendMail();
                
 
                returnString = "index";
            } else {
                 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Purchase Unsuccesful. "+invoice.getResponseText(), "Something went wrong"));

                System.out.println("Status" + invoice.getStatus());
                System.out.println("Response Message" + invoice.getResponseText());
                return "error";
            }
            
            
             } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Experiments.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
//        }
        } catch (Exception e) {
             FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unexpected Error occured. Please try again later ", "Something went wrong"));
             return "error";
        }
        return returnString;

    }
    
    
    public void sendMail() throws MessagingException, UnsupportedEncodingException
    {
        
          
                 Properties properties = new Properties();
                  properties.put("mail.smtp.host", host);
                 properties.put("mail.smtp.port", port);
                  properties.put("mail.smtp.auth", "true");
                 properties.put("mail.smtp.starttls.enable", "true");
        
        
        
        Session session = Session.getInstance(properties,
		  new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		  });
 
       String msgBody = "Hello from the time bomb! Added **********************************";
       
       
       
       
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("purcase.qrcodes@gmail.com", "purchase.qrcodes"));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress("brainychip@gmail.com", "brainychip@gmail.com"));
            msg.setSubject("Receipt of QR-Code");
            msg.setText(msgBody);
            
         
            Multipart mp = new MimeMultipart();

            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(msgBody, "text/html");
            mp.addBodyPart(htmlPart);

            
            MimeBodyPart attachment = new MimeBodyPart();
            attachment.setFileName("qrcode.jpeg");
            attachment.setContent(credit.getImage(), "image/jpeg");
            mp.addBodyPart(attachment);
            
            msg.setContent(mp);

            
            


         


            Transport.send(msg);
            
            System.out.println("Mail Successfully sent");
//        } catch (AddressException e) {
//            e.printStackTrace();
//        } catch (MessagingException e) {
//            e.printStackTrace();
//        } catch (UnsupportedEncodingException ex) {
//            Logger.getLogger(Experiments.class.getName()).log(Level.SEVERE, null, ex);
//            ex.printStackTrace();
//        }

      // return null;
   
        
                
                
                
                
        
    }
}
